<template>
    <el-dialog :close-on-click-modal="false" title="文件传输中心" v-model="show" width="620px" append-to-body draggable
        :before-close="onBeforeCloseEvent" align-center>
        <div class="file-upload-container">
            <div class="upload-actions">
                <!-- <el-button @click="handleFolderOpen" type="primary">选择文件</el-button>
                <input type="file" ref="folderInputRef" webkitdirectory style="display: none;"
                    @change="handleFolderSelect" /> -->
                <div style="flex: 1;">
                    <el-upload action="#" multiple :auto-upload="false" :show-file-list="false"
                        :on-change="onChangeBtn">
                        <el-button type="primary">
                            选择
                            <el-icon class="el-icon--right">
                                <Upload />
                            </el-icon>
                        </el-button>
                    </el-upload>
                </div>
                <el-button @click="startUploads" type="primary">一键上传</el-button>
                <!-- <el-button @click="pauseUploads">暂停</el-button>
                <el-button @click="clearAll">清空所有</el-button>
                <el-button @click="clearCompleted">清空已完成</el-button> -->
            </div>

            <!-- 文件列表 -->
            <div class="file-list">
                <el-table :data="fileList" height="300" show-overflow-tooltip>
                    <el-table-column prop="name" label="名称" />
                    <el-table-column prop="size" label="大小">
                        <template #default="{ row }">
                            {{ row.size < 1024 * 1024 ? (row.size / 1024).toFixed(2) + ' KB' : (row.size / (1024 *
                                1024)).toFixed(2) + ' MB' }} </template>
                    </el-table-column>
                    <el-table-column prop="percent" label="进度" width="200px">
                        <template #default="{ row }">
                            <el-progress :percentage="row.percent" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态" width="60px" align="center">
                        <template #default="{ row }">
                            <template v-if="row.status == 'ready'">
                                等待中..
                            </template>
                            <template v-else-if="row.status == 'success'">
                                <el-icon>
                                    <CircleCheckFilled color="green" />
                                </el-icon>
                            </template>
                            <template v-else-if="row.status == 'error'">
                                <el-icon>
                                    <WarningFilled color="red" />
                                </el-icon>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80px" align="center">
                        <template #default="{ row }">
                            <!-- <template v-if="row.status == 'ready'">
                                <el-button type="primary" link @click="">
                                    <el-icon size="16">
                                        <VideoPlay />
                                    </el-icon>
                                </el-button>
                            </template>
    <template v-else-if="row.status == 'process'">
                                <el-button type="primary" link @click="">
                                    <el-icon size="16">
                                        <VideoPause color="green" />
                                    </el-icon>
                                </el-button>
                            </template> -->

                            <el-button link @click="handleFileRemove(row)">
                                <el-icon size="16">
                                    <Close />
                                </el-icon>
                            </el-button>
                            <!-- <template v-else-if="row.status == 'success'">
                                <el-icon>
                                    <CircleCheckFilled color="green" />
                                </el-icon>
                            </template>
                            <template v-else-if="row.status == 'error'">
                                <el-icon>
                                    <WarningFilled color="yellow" />
                                </el-icon>
                            </template> -->
                            <!-- <el-button type="primary" link @click="">
                                <el-icon size="16">
                                    <VideoPause />
                                </el-icon>
                            </el-button> -->
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
    </el-dialog>
</template>

<script setup>
import { delFileResource, uploadUrl, uploadFileResource } from "@/api/system/fileresource.js";
const { proxy } = getCurrentInstance()
const show = ref(true)
const props = defineProps({
    folder: { type: String, required: false }
})

const emits = defineEmits(["onUploadComplete", "onBeforeClose"])

const folder = computed(() => props.folder)

// 文件列表
const fileList = ref([]);

const onChangeBtn = (file, mm) => {
    appendFile(file.raw);
}

//添加需要上传的文件
const appendFile = (files) => {
    // 判断 files 是否为 FileList 类型
    if (files instanceof FileList) {
        // 将 FileList 转换为数组
        let appends = Array.from(files);
        appends.forEach(item => {
            let fileObj = {
                name: item.name,
                size: item.size,
                file: item,
                percent: 0,
                status: 'ready',
            }
            fileList.value.push(fileObj);
        });
    } else if (files instanceof File) {
        let fileObj = {
            name: files.name,
            size: files.size,
            file: files,
            percent: 0,
            status: 'ready',
        }
        fileList.value.push(fileObj);
    }
    else if (Array.isArray(files) && files.every(file => file instanceof File)) {
        // 遍历文件数组，执行相应操作
        files.forEach(item => {
            let fileObj = {
                name: item.name,
                size: item.size,
                file: item,
                percent: 0,
                status: 'ready',
            }
            fileList.value.push(fileObj);
            // 在此处处理每个文件
            console.log(`文件名: ${file.name}`);
            // 例如，您可以将文件添加到上传队列或执行其他操作
        });
    } else {
        console.error('传入的参数必须是 File 或 FileList 类型');
    }
};

defineExpose({ appendFile })


// 文件选择时的回调
const handleFileChange = (file, fileListRef) => {
    // fileList.value = fileListRef;
};


const handleExceed = () => {
    proxy.$modal.msgWarning("最多上传5个文件")
}


// 文件移除时的回调
const handleFileRemove = (item) => {
    fileList.value = fileList.value.filter(s => s !== item);
};

// 文件上传前的回调
const beforeUpload = (file) => {
    // 可以在这里添加文件校验逻辑
    if (file.size > 10 * 1024 * 1024) {
        ElMessage.error('文件大小不能超过 10MB');
        return false;
    }
    return true;
};

// 暂停上传
const pauseUploads = () => {
    ElMessage.info('暂停上传功能需结合具体上传逻辑实现');
};

// 清空所有文件
const clearAll = () => {
    fileList.value = [];
};

// 清空已完成文件
const clearCompleted = () => {
    fileList.value = fileList.value.filter((file) => file.status !== 'success');
};

// 暂停单个文件上传
const pauseFile = (index) => {
    ElMessage.info(`暂停文件 ${fileList.value[index].name} 的上传`);
};

//一键上传
const startUploads = () => {
    let readyList = fileList.value.filter((file) => file.status === 'ready');
    const uploadPromises = readyList.map((file, index) => {
        return new Promise((resolve, reject) => {
            proxy.$upload.upload(
                file.file,
                { folder: folder.value },
                (percent) => {
                    file.percent = Number(percent);
                    console.log(`文件 ${index + 1} 的上传进度: ${percent}%`);
                }
            )
                .then((res) => {
                    file.status = "success";
                    emits("onUploadComplete", res.data, file.file)
                    resolve(res);
                })
                .catch((err) => {
                    file.status = "error";
                    proxy.$modal.msgWarning(`${file.name}上传失败：${err}`)
                    reject(err);
                });
        });
    });

    Promise.all(uploadPromises)
        .then((res) => {
            proxy.$modal.msgSuccess("文件上传完成");
            console.log('所有文件上传完成', res);
        })
        .catch((error) => {
            // proxy.$modal.msgWarning("文件上传异常")
            console.error('文件上传过程中出现错误:', error);
        });
};

//关闭前回调
const onBeforeCloseEvent = (done) => {
    emits("onBeforeClose");
    done();
}

</script>

<style scoped>
.file-upload-container {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
    border: 1px solid #ddd;
    border-radius: 8px;
}

.upload-actions {
    margin-bottom: 20px;
    display: flex;
}

.upload-demo {
    margin-bottom: 20px;
}

.file-list {
    margin-top: 20px;
}

.file-list ul {
    list-style: none;
    padding: 0;
}

.file-list li {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px;
    border-bottom: 1px solid #eee;
}

.file-list li:last-child {
    border-bottom: none;
}
</style>